package com.ratingbay.console.social;

import java.security.Principal;

import org.springframework.social.DuplicateStatusException;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.connect.web.ConnectInterceptor;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.WebRequest;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.Connection;

public class TwitterConnectInterceptor implements ConnectInterceptor<Twitter> {

    public void preConnect(ConnectionFactory<Twitter> provider, MultiValueMap<String, String> parameters, WebRequest request) {
        //
        //System.out.println("Yangxq Pre");
    	if (StringUtils.hasText(request.getParameter(POST_TWEET_PARAMETER))) {
			request.setAttribute(POST_TWEET_ATTRIBUTE, Boolean.TRUE, WebRequest.SCOPE_SESSION);
		}
    	
    }

    public void postConnect(Connection<Twitter> connection, WebRequest request) {
        //connection.updateStatus("I've connected with the Spring Social Showcase!");
        //System.out.println("Yangxq Post");
    	
    	String username=connection.fetchUserProfile().getUsername();
    	
    	if (request.getAttribute(POST_TWEET_ATTRIBUTE, WebRequest.SCOPE_SESSION) != null) {
			try {
				connection.updateStatus("I'm using http://ratingbay.com/user/"+username+" to see what my friends say about games. Check it out http://ratingbya.com");
			} catch (DuplicateStatusException e) {
			}
			request.removeAttribute(POST_TWEET_ATTRIBUTE, WebRequest.SCOPE_SESSION);
		}
    	System.out.println("shenhui Post");
    	
    }
    
    private static final String POST_TWEET_PARAMETER = "willingTweetRB";
    private static final String POST_TWEET_ATTRIBUTE = "twitterConnect." + POST_TWEET_PARAMETER;
}
